import { unref, computed } from 'vue'

import { useStore } from 'vuex'
// 需要传递原对象 不能消除指针
export function useUpload(listObj) {
  /**
   * 通过检测hasSuccess是否全都变为true
   * @returns true全部上传成功，false则为未全部上传
   */
  function checkAllSuccess() {
    return Object.keys(unref(listObj)).every(
      (item) => unref(listObj)[item].hasSuccess
    )
  }

  /**
   * 删除数组里存放对应的file
   * @param {*} file el-upload打包的文件
   * @returns
   */
  function removeFile(file) {
    const uid = file.uid
    const objKeyArr = Object.keys(unref(listObj))
    for (let i = 0, len = objKeyArr.length; i < len; i++) {
      if (listObj.value[objKeyArr[i]].uid === uid) {
        delete listObj.value[objKeyArr[i]]
        return
      }
    }
  }

  /**
   * 上传成功后在这里标记
   * @param {*} response el-upload上传成功返回值
   * @param {*} file el-upload打包的文件
   * @returns
   */
  function uploadSuccess(response, file) {
    const uid = file.uid
    const objKeyArr = Object.keys(unref(listObj))
    for (let i = 0, len = objKeyArr.length; i < len; i++) {
      if (listObj.value[objKeyArr[i]].uid === uid) {
        listObj.value[objKeyArr[i]].url = response.data
        listObj.value[objKeyArr[i]].hasSuccess = true
        return
      }
    }
  }

  /**
   * 实例化给el-upload使用的勾子
   * @param {*} file el-upload打包的文件
   * @returns
   */
  function uploadBefore(file) {
    const _URL = window.URL || window.webkitURL
    const fileName = file.uid
    listObj.value[fileName] = {}
    return new Promise((resolve, reject) => {
      listObj.value[fileName] = { hasSuccess: false, uid: file.uid }

      resolve(true)
    })
  }

  return {
    checkAllSuccess,
    removeFile,
    uploadSuccess,
    uploadBefore,
  }
}

export function uploadNetTools() {
  const store = useStore()

  /**
   * 创建请求头，填充token
   */
  const header = computed(() => {
    const header = { ContentType: 'multipart/form-data' }
    header['auth'] = store.getters.token
    return header
  })

  /**
   * 提取上传地址
   */
  const uploadUrl = computed(() => {
    return process.env.VUE_APP_BASE_URL + '/emrweb/file/upload'
  })
  return {
    header,
    uploadUrl,
  }
}
